<template>
  <div class="search-suggestion">
    <van-cell v-for="(value,index) in suggestions" :key="index"
              :title="value" icon="search" @click="$emit('search',value)">
      <template #title>
        <span v-html="hightLight(value)"></span>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestionsAPI } from '../../../api/index.js'
import _ from 'lodash'

export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      default: ''
    }
  },
  /*
  * 防抖
  * debounce(function(){回调函数}，延时事件)
  * */
  watch: {
    searchText: {
      handler: _.debounce(function () {
        // 调用联想查询方法
        this.loadSearchSuggestions()
      }, 500),
      immediate: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  methods: {
    async loadSearchSuggestions () {
      try {
        const { data: res } = await getSearchSuggestionsAPI({
          q: this.searchText
        })
        this.suggestions = res.data.options
        if (res.data.options.length === 0 || res.data.options[0] === null) {
          this.suggestions.splice(0, 1, this.searchText)
        }
      } catch (err) {
        console.log(err)
      }
    },
    hightLight (value) {
      const str = value.split(this.searchText).join(`<span style="color: red;">${this.searchText}</span>`)
      return str
    }
  }
}
</script>

<style scoped lang="less"></style>
